
/**
 * 扩展jquery
 */
$.fn.qdata = function(){
	var res = {};
	
	var data = $(this).attr('data');
	if(data){
		var options = data.split(';');
		for(var i=0; i<options.length; i++){
			if(options[i]){
				var opt = options[i].split(':');
				res[opt[0]] = opt[1];
			}
		}
	}
	
	return res;
};
$.fn.qser = function(){
	var obj = {};
	
	var objs = $(this).serializeArray();
	if(objs.length != 0){
		for(var i=0; i<objs.length; i++){
			obj[objs[i].name] = objs[i].value;
		}
	}

	return obj;
};


/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic, elements) {
    var a = [];
    if (this.length === 0) {
        return a;
    }

    var form = this[0];
    var els = semantic ? form.getElementsByTagName('*') : form.elements;
    if (!els) {
        return a;
    }

    var i,j,n,v,el,max,jmax;
    for(i=0, max=els.length; i < max; i++) {
        el = els[i];
        n = el.name;
        if (!n || el.disabled) {
            continue;
        }

        if (semantic && form.clk && el.type == "image") {
            // handle image inputs on the fly when semantic == true
            if(form.clk == el) {
                a.push({name: n, value: $(el).val(), type: el.type });
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            }
            continue;
        }

        v = $.fieldValue(el, true);
        if (v && v.constructor == Array) {
            if (elements)
                elements.push(el);
            for(j=0, jmax=v.length; j < jmax; j++) {
                a.push({name: n, value: v[j]});
            }
        }
        else if (v !== null && typeof v != 'undefined') {
            if (elements)
                elements.push(el);
            a.push({name: n, value: v, type: el.type, required: el.required});
        }
    }

    if (!semantic && form.clk) {
        // input type=='image' are not found in elements array! handle it here
        var $input = $(form.clk), input = $input[0];
        n = input.name;
        if (n && !input.disabled && input.type == 'image') {
            a.push({name: n, value: $input.val()});
            a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
        }
    }
    return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
    //hand off to jQuery.param for proper encoding
    return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
    var a = [];
    this.each(function() {
        var n = this.name;
        if (!n) {
            return;
        }
        var v = $.fieldValue(this, successful);
        if (v && v.constructor == Array) {
            for (var i=0,max=v.length; i < max; i++) {
                a.push({name: n, value: v[i]});
            }
        }
        else if (v !== null && typeof v != 'undefined') {
            a.push({name: this.name, value: v});
        }
    });
    //hand off to jQuery.param for proper encoding
    return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *      <input name="A" type="text" />
 *      <input name="A" type="text" />
 *      <input name="B" type="checkbox" value="B1" />
 *      <input name="B" type="checkbox" value="B2"/>
 *      <input name="C" type="radio" value="C1" />
 *      <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $('input[type=text]').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $('input[type=checkbox]').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $('input[type=radio]').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *    array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = $.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
            continue;
        }
        if (v.constructor == Array)
            $.merge(val, v);
        else
            val.push(v);
    }
    return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (successful === undefined) {
        successful = true;
    }

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1)) {
            return null;
    }

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) {
            return null;
        }
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
                var v = op.value;
                if (!v) { // extra pain for IE...
                    v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
                }
                if (one) {
                    return v;
                }
                a.push(v);
            }
        }
        return a;
    }
    return $(el).val();
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function(includeHidden) {
    return this.each(function() {
        $('input,select,textarea', this).clearFields(includeHidden);
    });
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
    var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (re.test(t) || tag == 'textarea') {
            this.value = '';
        }
        else if (t == 'checkbox' || t == 'radio') {
            this.checked = false;
        }
        else if (tag == 'select') {
            this.selectedIndex = -1;
        }
        else if (includeHidden) {
            // includeHidden can be the value true, or it can be a selector string
            // indicating a special test; for example:
            //  $('#myForm').clearForm('.special:hidden')
            // the above would clean hidden inputs that have the class of 'special'
            if ( (includeHidden === true && /hidden/.test(t)) ||
                 (typeof includeHidden == 'string' && $(this).is(includeHidden)) )
                this.value = '';
        }
    });
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
            this.reset();
        }
    });
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) {
    if (b === undefined) {
        b = true;
    }
    return this.each(function() {
        this.disabled = !b;
    });
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
    if (select === undefined) {
        select = true;
    }
    return this.each(function() {
        var t = this.type;
        if (t == 'checkbox' || t == 'radio') {
            this.checked = select;
        }
        else if (this.tagName.toLowerCase() == 'option') {
            var $sel = $(this).parent('select');
            if (select && $sel[0] && $sel[0].type == 'select-one') {
                // deselect all other options
                $sel.find('option').selected(false);
            }
            this.selected = select;
        }
    });
};
/**
 * 扩展一些js默认的方法
 * 1.string.contains
 * 2.string.endWith
 * 3.string.startWith
 * 4.string.inArray
 */
// string--------------------------------------------------------------------------------
/**
 * contains方法
 * @param s
 * @returns {Boolean}
 */
String.prototype.contains = function(s){
	return this.indexOf(s) != -1;
};

/**
 * endWith方法
 * @param s
 * @returns {Boolean}
 */
String.prototype.endWith=function(s){  
    if(this && s && this.length > s.length){
    	if(this.substring(this.length-s.length)==s){
    		return true;
    	}
    }
    
    return false;
};

/**
 * 判断string是否以s开头
 * @param s
 * @returns {Boolean}
 */
String.prototype.startWith=function(s){  
    if(this && s && this.length > s.length){
    	if(this.substr(0,s.length)==s){  
    		return true;
    	}  
    }
    
    return false;
};

/**
 * 判断string是否在一个array内
 * @param array
 * @returns {Boolean}
 */
String.prototype.inArray = function(array){
	if(this && array){
		for(var i=0; i<array.length; i++){
			if(this == array[i]){
				return true;
			}
		}
	}
	
	return false;
};
/**
 * bfsuol for bootstrap = bfsu
 * @author qiaowenbin
 * @version 0.0.3.20140701
 */ 
;(function($,window) {
var bfsu={};
if(!window.bfsu){
	window.bfsu = bfsu;
}

// bfsu public------------------------------------------------------------------------------------------------
/**
 * ajaxSubmit() provides a mechanism for immediately submitting
 * an HTML form using AJAX.
 */
bfsu.ajaxSubmit = function(options) {
	var opts = {
			url:undefined,//提交地址，如果是form表单提交，可以不写，则使用form的action属性
    		form:undefined,//提交的表单id或者是name
    		target:false,//返回结果容器id，如果是html类型，则返回结果直接填充对应的容器
	    	method:undefined,//提交方式，如果是from表单提交，可以不写，则使用from的method属性
	    	dataType:'html',//数据类型，默认html，支持jquery的ajax类型
	    	data:undefined,//提交的数据[{name:'name1',value:'val1'},{name:'name2',value:'val2'}]
	    	onSubmit:false,//提交前执行
	    	onSuccess:false,//提交成功后，返回结果处理前执行
	    	onCompleted:false,//提交成功后，返回结果处理后执行
	    	onError:false//提交失败是执行
    };
	opts=bfsu.getOptions(options);
	//如果是form表单提交，则信息默认从表单获取
	var $form = $("#"+opts.form) || $('form[name='+opts.form+']');
	if ($form && $form.length>0) {
		//alert("$form.length="+$form.attr('action'));
		if(opts.data){
			$.each(opts.data,function(index,q){
				var $element = $form.find('[name='+q.name+']');
				if($element.length>0){
					$element.val(q.value);
				}else{
					$("<input type='hidden' name='"+q.name+"' value='"+q.value+"' />").appendTo($form);
				}
			});
		}
		opts.url=$form.attr('action');
		opts.data=$form.formSerialize();
        
        //alert($form.formSerialize() +'--' +$form.attr('method') +'--'+ $form.attr('action'));
    }
	
	//alert("opts.url="+opts.url  );
	//提交前执行
    if (!opts.url) {
        return this;
    }
    
    //提交前执行
    if (opts.onSubmit && opts.onSubmit.apply(this, opts) === false) {
        return this;
    }
    //开始远程调用
    $.ajax({
    	type	:opts.method,
    	url		:opts.url,
    	dataType:opts.dataType,
    	data	:opts.data,
    	success	:function(data,textStatus){
    		if(opts.onSuccess && opts.onSuccess.apply(this,[data,textStatus]) === false){
    			return;
    		}
    		if(opts.dataType=='html' && opts.target){
    			var $target = $('#'+opts.target);
    			$target.empty();
    			$target.html(data);
    		}
    		if(opts.onCompleted){
    			opts.onCompleted.apply(this,[data,textStatus]);
    		}
    	},
    	error:opts.onError
    });
    
    return this;
};
/**
 * ajax加载html内容到指定容器
 * @param href 要加载的页面url
 * @param target 获取到的html填充目标
 */
bfsu.html=function(href,target,text){
	if(!target){
		target='bscenter';
	}
	$('#'+target).html("<img  src='"+PROJECT_HOME+"/style/load.gif' width='100%' />");
	$.ajax({
		url : href,
		data : {},
		type : 'post',
		dataType : 'html',
		success : function(html){
			$('#'+target).html(html);
		}
	});
}
bfsu.ajaxmsg = function(json){
	if(json){
		if(json.result == 'success'){
			bfsu.msgok(json.message);
		}else{
			bfsu.msger(json.message);
		}
	}else{
		bfsu.msger('ajax fail!');
	}
};

// bfsu crud list----------------
// bfsu crud options
bfsu.options = {
	id:undefined,
	url : undefined,
	queryForm:'queryForm',
	inputForm:'inputForm',
	listId:'bslist',
	pageSize : 10,
	currentPage : 1,
	cssDatePicker:'date',
	cssTime:'time',
	cssNumber:'number',
	cssEditor:'editor',
	cssTinyEditor:'tinyeditor',
	cssQuestionEditor:'questioneditor',
	
	/* ajax */
	source:undefined,
	form:undefined,
	method:'POST',
	dataType:'html'
};
bfsu.getOptions=function(options){
	var opts = {};
	if(options){
		if(typeof option == 'string' ){
			opts = eval(options); 
		}else{
			opts = options;
		}
	}
	idopts = {};
	
	if(options&&options.id){
		var id = options.id ;
		idopts = {
			queryForm:id+'queryForm',
			inputForm:id+'inputForm',
			listId:id+'bslist'
		};
	}
	return $.extend({},bfsu.options,idopts,opts);
}
// bfsu crud list
bfsu.list = function(options){
	var opt=bfsu.getOptions(options);
	var opts={
			url		: opt.url,
			form	:opt.queryForm,
			target  :opt.listId,
			data	: [{name:'pageSize',value:opt.pageSize},{name:'currentPage',value:opt.currentPage}],
			dataType: 'html'
		}
	opts.onCompleted = function(html,status){
		if(opt.onCompleted){
			opt.onCompleted.apply(this,[html,status]);
		}
	};
	bfsu.ajaxSubmit(opts);
};

// bfsu crud page---------------
// bfsu crud go
bfsu.go = function(options){
	var opt=bfsu.getOptions(options);
	var $page=$('#bsmodal').find('.crudpage');
	if(!$page.val()){
		$page=$('input.crudpage');
	}
	var page = parseInt($.trim($page.val()));
	var $size=$('#bsmodal').find('.crudsize');
	if(!$size.val()){
		$size=$('input.crudsize');
	}
	var size = parseInt($.trim($size.val()));
	
	if(size&&size!=null){
		opt.pageSize 		= size;
	}
	if(page&&page!=null){
		opt.currentPage 	= page;
	}
	
	bfsu.query(opt);
};
// bfsu crud page
bfsu.page = function(options){
	var opt=bfsu.getOptions(options);;
	var $size=$('#bsmodal').find('.crudsize');
	if(!$size.val()){
		$size=$('input.crudsize');
	}
	var size = parseInt($.trim($size.val()));
	
	opt.pageSize 		= size;
	bfsu.query(opt);
};


// bfsu crud add and edit-----------
/**
 * 添加
 * @param url
 * @param title
 */
bfsu.add = function(url, title,inputFormId){
	if(url && title){
		bfsu.dialog({url:url,title:title,onOk:function(){
			bfsu.save({id:inputFormId});
		}});
	}
};
/**
 * 预览
 * @param url
 * @param title
 */
bfsu.view = function(url, title){
	if(url && title){
		bfsu.dialog({url:url,title:title,showOk:false});
	}
};
/**
 * 编辑
 * @param url
 * @param title
 */
bfsu.edit = function(url, title,inputFormId){
	if(url && title){
		if(url.endWith('input')){// toobar修改
			var $input = $('input.bscheck:checked');
			var length = $input.length;
			if(length != 1){
				bfsu.msger('请选择要修改的一条数据！');
			}else{
				url += '/' + $input.qdata().id;
				bfsu.dialog({url:url,title:title,onOk:function(){
					bfsu.save({id:inputFormId});
				}});
			}
		}else{
			bfsu.dialog({url:url,title:title,onOk:function(){
				bfsu.save({id:inputFormId});
			}});
		}
	}
};

/**
 * 批量编辑
 * @param url
 * @param title
 */
bfsu.batchEdit = function(url, title,id){
	if(url && title){
		if(url.endWith('input')){// toobar修改
			var $input = $('input.bscheck:checked');
			var length = $input.length;
			if(length < 1){
				bfsu.msger('请选择要修改的数据！');
			}else{
				url+=bfsu.selectedIds();
				bfsu.dialog({url:url,title:title,onOk:function(){
					bfsu.save({id:id});
				}});
			}
		}else{
			bfsu.dialog({url:url,title:title,onOk:function(){
				bfsu.save({id:id});
			}});
		}
	}
};
/**
 * 初始化查询
 * - 日期输入控件的格式化
 * - 查询按钮的事件添加
 * - 由于使用ajax提交，控件的回车时间变为Tab
 * - 停止其他的默认提交行为
 */
bfsu.initQuery = function(options){
	var opts = bfsu.getOptions(options);
	var $query = $("#"+opts.queryForm);
	$query.find('input[type!=button][type!=submit][type!=reset][type!=radio][type!=checkbox]').addClass('form-control');
	$query.find('select').addClass('form-control');
	//初始化日期控件
	$query.find('input.'+opts.cssDatePicker).datetimepicker({format: 'yyyy-mm-dd',minView:2,autoclose:true,todayBtn:true,language:'zh-CN'});
	$query.find('input.'+opts.cssTime).datetimepicker({format: 'yyyy-mm-dd hh:ii:ss',autoclose:true,todayBtn:true,language:'zh-CN'});
	//$input.find('input.'+options.cssNumber).numberpicker();
	//多选框初始化
	//$query.find("select.multiselect").multiselect({enableCaseInsensitiveFiltering:true,maxHeight:250,nonSelectedText:'请选择',numberDisplayed:6});	//form中加入回车事件转变成Tab
	$query.find('input[type!=button][type!=submit][type!=reset]').keyup(function(event){
		if(event.keyCode == 13){
			event.preventDefault();//阻止默认的提交动作
		}
    });
	//加入低版本浏览器placeholder支持
	if( !('placeholder' in document.createElement('input')) ){
		$('input[placeholder],textarea[placeholder]').each(function(){
			var that = $(this),   
			text= that.attr('placeholder');    
			that.tooltip({title:text,trigger:'hover'});
			   
		});   
	}
};

/**
 * 初始化添加或者修改页面
 * - 日期输入控件的格式化
 * - 提交按钮的事件添加
 * - 由于使用ajax提交，控件的回车时间变为Tab
 * - 停止其他的默认提交行为
 * - 校验信息的初始化
 */
bfsu.initInput=function(options){
	var opts = bfsu.getOptions(options);

	
	var $input = $("#"+opts.inputForm);
	//处理页面样式
	//$input.find('table').css('width','100%');
	$input.find('input[type!=button][type!=submit][type!=reset][type!=radio][type!=checkbox]').addClass('form-control');
	$input.find('select').addClass('form-control');
	//$input.find('td').each(function(i,item){
	//	var $item=$(item);
	//	$item.html("<div class='form-group'>"+$item.html()+"</div>");	
	//});
	//多选框初始化
	$input.find("select.multiselect").multiselect({enableCaseInsensitiveFiltering:true,maxHeight:250,nonSelectedText:'请选择',numberDisplayed:6});	//加入日期
	$input.find('input.'+opts.cssDatePicker).datetimepicker({format: 'yyyy-mm-dd',minView:2,autoclose:true,todayBtn:true,language:'zh-CN'});
	$input.find('input.'+opts.cssTime).datetimepicker({format: 'yyyy-mm-dd hh:ii:ss',autoclose:true,todayBtn:true,language:'zh-CN'});
	//$input.find('input.'+options.cssNumber).numberpicker();
	
	//加入富文本编辑器
	if(typeof UE != 'undefined'){
    	$input.find('.'+opts.cssEditor).each(function(i,item){
    		var $item = $(item);
    		var id = $item.attr('id');
    		if(!id){
    			id = 'editor_' + Math.random();
    			$item.attr('id',id);
    		}
    		UE.getEditor(id,{
                //这里可以选择自己需要的工具按钮名称
                toolbars:[['source', '|', 'undo', 'redo', '|',
                'bold', 'italic', 'underline', 'fontborder', 'strikethrough', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist',   'pasteplain', '|',
                'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
                'customstyle', 'paragraph', 'fontfamily', 'fontsize',  '|',
                'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
                'insertimage','attachment', '|',
                'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', '|',
                'print', 'preview','fill'
                ]],
                
                autoFloatEnabled:true,
                scaleEnabled:false,
                autoHeightEnabled:false,
                fullscreen:false,
                wordCount:false,//关闭字数统计
                elementPathEnabled:false,//关闭elementPath
                initialFrameHeight:150//默认的编辑区域高度
                //initialFrameWidth:'99%'//默认的编辑区域高度
            });
    		
    	});
    	$input.find('.'+opts.cssTinyEditor).each(function(i,item){
    		var $item = $(item);
    		var id = $item.attr('id');
    		if(!id){
    			id = 'editor_' + Math.random();
    			$item.attr('id',id);
    		}
    		UE.getEditor(id,{
                //这里可以选择自己需要的工具按钮名称,此处仅选择如下五个
                toolbars:[['Undo', 'Redo','|','bold', 'italic', 'underline','|', 'forecolor', 'backcolor','|','customstyle', 'paragraph', 'fontfamily', 'fontsize','|','link', 'unlink','emotion', '|', 'preview']],
                
                autoFloatEnabled:true,
                scaleEnabled:false,
                autoHeightEnabled:false,
                fullscreen:false,
                wordCount:false,//关闭字数统计
                elementPathEnabled:false,//关闭elementPath
                initialFrameHeight:200//默认的编辑区域高度
                //initialFrameWidth:'99%'//默认的编辑区域高度
            });
    	});
    	$input.find('.'+opts.cssQuestionEditor).each(function(i,item){
    		var $item = $(item);
    		var id = $item.attr('id');
    		if(!id){
    			id = 'editor_' + Math.random();
    			$item.attr('id',id);
    		}
    		UE.getEditor(id,{
    			//这里可以选择自己需要的工具按钮名称
    			toolbars:[['source', '|', 'undo', 'redo', '|','insertimage','insertvideo','music','attachment', '|',
                'bold', 'italic', 'underline', 'fontborder', 'strikethrough', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist',   'pasteplain', '|',
                'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
                'customstyle', 'paragraph', 'fontfamily', 'fontsize',  '|',
                'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
                'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', '|',
                ,'fill'
                ]],
    		                
    			autoFloatEnabled:false,
    			scaleEnabled:false,
    			autoHeightEnabled:true,
    			fullscreen:false,
    			wordCount:false,//关闭字数统计
    			elementPathEnabled:false,//关闭elementPath
    			initialFrameHeight:150,//默认的编辑区域高度
//    			initialFrameWidth:800,//默认的编辑区域宽度
    			zIndex : 100
    			
    		});
    	});
	}
	//form中加入回车事件变为Tab
	$input.find('input[type!=button][type!=submit][type!=reset]').keydown(function(event){
   		if(event.keyCode ==13){
           event.keyCode = 9;
           event.preventDefault();//阻止默认的提交动作
        }
   	});
	
   	//加入校验
	$input.validation();
	//加入低版本浏览器placeholder支持
	if( !('placeholder' in document.createElement('input')) ){
		$('input[placeholder],textarea[placeholder]').each(function(){
			var that = $(this),   
			text= that.attr('placeholder');    
			that.tooltip({title:text,trigger:'hover'});
			   
		});   
	}
};
// bfsu crud save
bfsu.save = function(options){
	var opts = {
			message:		false,
			form:			undefined,
			target:		undefined,
			method:		undefined,
			url:				undefined,
			onCompleted:undefined,
			onSubmit:		undefined,
			onSuccess:	undefined,
			onError:		undefined
		};
	if(options&&options.url){
		opts.url=options.url;
	}else{
		options=bfsu.getOptions(options);
		opts.form=options.inputForm;
	}
	opts.method	= opts.method || 'POST';
	opts.dataType='json';
	opts.onCompleted=function(data,textStatus){
		if(data){
			if(data.result == 'success'){
				$modal.modal('hide');
				bfsu.msgok(data.message);
				bfsu.go();
			}else{
				$('button.bsok').attr("disabled",false);
				bfsu.msger(data.message);
				return false;
			}
		}else{
			bfsu.msger('ajax fail!');
			return false;
		}
    }
	bfsu.ajaxSubmit(opts);
};

// bfsu crud query-----------
// bfsu crud query
bfsu.query_extend = function(options, title){
	var opt=bfsu.getOptions(options);
	bfsu.dialog({url:opt.url,title:title}, function(){
		var $form = $('#bsmodal form');
		opt.url = $form.qdata().url;
		bfsu.list(opt);
	});
};
// bfsu crud query
bfsu.query = function(options){
	var opt=bfsu.getOptions(options);
	if(!opt.url){
		var $form=$("#"+opt.queryForm);
		opt.url=$form.qdata().url;
		
	}
	if(!opt.url){
		var $list=$("#"+opt.listId);
		opt.url=$list.qdata().url;
	}
	bfsu.list(opt);
};

// bfsu crud del---------
/**
 * 删除
 * @param url 删除地址
 * @param msg 确认框消息
 * @param isBatchDel 是否批量删除
 */
bfsu.del = function(url, msg,isBatchDel,options){
	var opt=bfsu.getOptions(options);
	if(url && msg){
		
		var ids = bfsu.selectedIds(opt);
		if(isBatchDel){
			if(!ids){
				bfsu.msger("请选择要操作的数据！");
				return;
			}
		}else{
			if((url.endWith('delete')||url.endWith('delete/'))&&!ids){
				bfsu.msger("请选择要操作的数据！");
				return;
			}
		}
		
		opt.url=url;
		
		if(ids.length>1){// 删除多条
			opt.url+=ids;
			bfsu.confirm(msg, function(){
				bfsu.save(opt);
			});
		}else{
			bfsu.confirm(msg, function(){
				
				bfsu.save(opt);
			});
		}
		
	}
};
// bfsu crud del ids
bfsu.selectedIds = function(options){
	var opt=bfsu.getOptions(options);
	var ids = '?';
	$('#'+opt.listId).find('input.bscheck').each(function(){
		var $this = $(this);
		if($this.prop('checked')){
			var id = $this.qdata().id;
			if(id) ids = ids + 'ids=' + id + '&';
		}
	});
	return ids == '?' ? '' : (ids.substring(0, ids.length-1));
};



/**
 * bfsu.on
 * 事件绑定
 */
bfsu.on = function(obj, event, func){
	$(document).off(event, obj).on(event, obj, func);
};


// bfsu crud bind----------------------------------------------------------------------------------------------
bfsu.on('input.bscheckall','change',function(){
	var $this = $(this);
	var isCheck = $this.prop('checked');
	
	if(isCheck){
		$this.parents('table').find('input.bscheck').each(function(){
			$(this).prop('checked', true);
		});
	}else{
		$this.parents('table').find('input.bscheck').each(function(){
			$(this).prop('checked', false);
		});
	}
});
/**
 * 对bootstrap的封装
 * 1.bstree
 * 2.bstab
 * 3.bsmsg
 * @author qiaowenbin
 * @version 0.0.3.20140701
 */
/**
 * 1.bstree
 */


/**
 * 2.bstab
 */
bfsu.addTab = function(id, title, url){
	if(title && url != '#'){
		var tabid = 'bstabdiv_' + id;
		
		// append tabdiv
		var tabdiv = '<div class="tab-pane" id="' + tabid + '"><iframe src="'+url+'" frameborder="0" style="border:0;width:100%;height:100%;"></iframe></div>';
		$('#bstabdiv').append(tabdiv);
		
		// append tabtitle
		var tabtitle = '<li><a href="#' + tabid + '" data-toggle="tab">' + title + '</a></li>';
		$('#bstabtitle').append(tabtitle);
		
		// show tab
		$('#bstabtitle li:last a').tab('show');
	}
};

/**
 * 3.bs msg
 */
// bfsu msg options
bfsu.msgoptions = {
	url 	: undefined,
	fade	: 'fade',
	close	: true,
	title	: '',
	btn		: false,
	showOk	: true,
	onOk:undefined,
	showCancel	: true,
	onCancel:undefined,
	msg		: 'loading......',
	big		: true,
	show	: false,
	remote	: false,
	backdrop: 'static',
	keyboard: true,
	buttons:[]
};
// bs弹出窗口
bfsu.dialog = function(opt){

	opt = $.extend({}, bfsu.msgoptions,opt);
	var start = '<div class="modal '+opt.fade+'" id="bsmodal" tabindex="-1" role="dialog" aria-labelledby="bsmodaltitle" aria-hidden="true">';
	if(opt.big){
		start += '<div class="modal-dialog modal-lg"><div class="modal-content">';
	}else{
		start += '<div class="modal-dialog modal-sm"><div class="modal-content">';
	}
	
	
	var head = '<div class="modal-header">';
	if(opt.close){
		head += '<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>';
	}
	head += '<h3 class="modal-title" id="bsmodaltitle">'+opt.title+'</h3></div>';
	
	var body = '<div id="bsmodalbody" class="modal-body">加载中</div>';
	var foot='<div class="modal-footer">';
	if(opt.showOk){
		foot += '<button type="button" class="btn btn-primary bsok">确定</button>';
	}
	if(opt.showCancel){
		foot += '<button type="button" class="btn btn-default bscancel">取消</button>';
	}
	if(opt.buttons&&opt.buttons.length>0){
		for(var item in opt.buttons){
			foot += '<button type="button" class="btn btn-default bs'+item.title+'">'+item.title+'</button>';
		}
	}
	var end = '</div></div></div></div>';
	$('body').append(start + head + body + foot + end);
	if(opt.msg){//填充弹出框内容
		$("#bsmodalbody").html(opt.msg);
	}
	if(opt.url){//填充弹出框内容
		bfsu.ajaxSubmit({url:opt.url, dataType:'html',target:'bsmodalbody'});
	}
	// init
	$modal=$("#bsmodal");
	$modal.modal(opt);
	
	// bind
	if(opt.showOk){
		bfsu.on('button.bsok', 'click', function(){
			
			if(opt.onOk) {
				$('button.bsok').attr("disabled",true);
				if(!$("#bsmodal form").valid()){
					$('button.bsok').attr("disabled",false);
					return false;
				}
				opt.onOk();
			}
			
		});
	}
	if(opt.showCancel){
		bfsu.on('button.bscancel', 'click', function(){
			if(opt.onCancel) {
				opt.onCancel();
			}
			$modal.modal('hide');
		});
	}
	if(opt.buttons&&opt.buttons.length>0){
		for(var item in opt.buttons){
			bfsu.on('button.bs'+item.title, 'click', function(){
				if(item.onClick) {
					if(item.onClick()){
						$modal.modal('hide');
					}
				}
			});
		}
	}
	bfsu.on('#bsmodal', 'hidden.bs.modal', function(){
		$modal.remove();
	});
	// show
	$modal.modal('show');
};
// bs msg alert
bfsu.alert = function(options,ok){
	// options
	var opt = $.extend({}, bfsu.msgoptions);
	if(typeof options == 'string'){
		opt.msg = options;
	}else{
		$.extend(opt, options);
	}
	opt.title='提示信息';
	opt.showOk=true;
	opt.showCancel=false;
	opt.onOk=ok;
	opt.big=false;
	bfsu.dialog(opt);
};
// bs msg confirm
bfsu.confirm = function(options, ok, cancel){
	// options
	var opt = $.extend({}, bfsu.msgoptions);
	if(typeof options == 'string'){
		opt.msg = options;
	}else{
		$.extend(opt, options);
	}
	opt.title='确认信息';
	opt.showOk=true;
	opt.showCancel=true;
	opt.onOk=ok;
	opt.onCancel=cancel;
	opt.big=false;
	bfsu.dialog(opt);
};
// bs msg msg
//bs msg msg
bfsu.msg = function(msg, type){
	var dmsg = msg ? msg : 'msg';
	var dtype = type ? type : 'ok';
	
	if(dtype == 'ok'){
		$.gritter.add({  
		    title: '提示消息',  
		    text: dmsg,  
		    sticky: false,  
		    time: 3000,  
		    speed:500,  
		    class_name: 'gritter-success gritter-light'
		});  
	}else{
		$.gritter.add({  
		    title: '错误提醒',  
		    text: dmsg,  
		    sticky: false,  
		    time: 3000,  
		    speed:500,  
		    class_name: 'gritter-error gritter-light'
		});
	}
};
// bs msg msgok
bfsu.msgok = function(msg){
	bfsu.msg(msg, 'ok');
};
// bs msg msger
bfsu.msger = function(msg){
	bfsu.msg(msg, 'er');
};

// qrecord
/**
 * 使用方法：
 * 1.页面head：<@head import=true qrecord=true>
 * 2.页面body内：<@hrecord/>
 * 3.js：bfsu.qrecord('id');
 * 4.id为想要显示录音插件的地方
 */
bfsu.qrecord = function(id){
	$('#myRecordDiv').appendTo($('#'+id)).show();
};
})(jQuery,window);  
